/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
import {
  getProductMenuField,
  getPageInfo,
  delTreeList,
  productMenuStatistics,
  setPagerelationPartOrWiki,
  relationProduct,
  relationMateriel,
  amountCount,
  productTypeFaultRecord
} from '@src/api/ProductV2Api.js';
import {
  getProductFields
} from '@src/api/ProductApi'

/* util */
import AuthUtil from '@src/util/auth';
import Filter from '@src/filter/filter.js';
import { parse } from '@src/util/querystring';
import {
  isShowReport,
  isShowCustomerRemind,
  isShowPlanTask
} from '@shb-lib/version'
import { ctiCallOut } from '@src/util/ctisdk';

import { getAllGrayInfo } from '@src/util/grayInfo';
import { getRootWindow } from '@src/util/dom';

/* component */
import ProductMenuView from '@src/modules/productV2/productMenuView/components/ProductMenuView.vue';
import ProductMenuInfoRecord from '@src/modules/productV2/productMenuView/components/ProductMenuInfoRecord.vue';
import MiniTable from '@src/modules/productV2/productMenu/WorkTree/compoment/MiniTable';
import PublicDialog from '@src/modules/productV2/productMenu/WorkTree/compoment/PublicDialog';
import NoDataView from '@src/component/common/NoDataViewNew';

import MaterialDialog from '@src/component/form/components/FormMaterialsBill/MaterialDialog.vue';
import FormMaterialsBillView from '@src/component/form/components/FormMaterialsBill/FormMaterialsBillView.vue';
import TreeList from '@src/modules/faultLibrary/components/TreeList.vue';

import BaseBarV3 from '@src/component/common/BaseTabBar/BaseTabBarV3.vue'
import BaseTileLayoutTabBar from '@src/component/common/BaseTabBar/BaseTileLayoutTabBar.vue'
import { BaseTabBarUsualEnum, StorageHttpParamsForTerminalType, StorageHttpParamsForModuleType } from '@src/component/common/BaseTabBar/enum'
import { getStorageForDetailTabbar, setStorageForDetailTabbar } from '@src/api/SystemApi'
import { computedTabList } from '@src/util/tabBarUtils'
import { cloneDeep } from 'lodash'
import { useStateSystemViewLayout } from 'pub-bbx-utils'

/* mixin */
import tourGuide from '@src/mixins/tourGuide'
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { materialFields } from './materialFields';
/* mixin */
import { VersionControlTaskMixin } from '@src/mixins/versionControlMixin'
import * as FormUtil from '@src/component/form/util'

const ENCRYPT_FIELD_VALUE = '***';

import {
  TASK_GUIDE_DETAIL
} from '@src/component/guide/taskV2Store';

let getUrlObj;
import FormCellChange from '@src/component/compomentV2/FormCellChange/index.vue';

export default {
  name: 'product-detail-view',
  inject: ['initData'],
  mixins: [
    tourGuide, 
    ThemeMixin,
    VersionControlTaskMixin
  ],
  data() {
    getUrlObj = this.$getUrlObj(window);
    let id = getUrlObj.id;
    return {
      loading: false,
      pending: false,
      collapse: true,
      task: {},
      dataInfo: {
        id
      },
      fieldHideIdArr: [],
      taskState: {
        value: this.initData?.task?.state || ''
      },
      fields: [], // 工单表单字段
      hasCallCenterModule: localStorage.getItem('call_center_module') == 1,
      leftActiveTab: 'product-view',
      rightActiveTab: 'record',
      collapseDirection: '',
      statistics:{},
      guideSearchModelSave: false,
      guideDropdownMenu: false,
      isGuide: false,
      dialogType: 'linkPart',
      visibleProp: false,
      isHaveDetails: true, // 产品类型是否有详情
      auths:{},
      treePath:[],
      showAddress:false,
      showLinkman:false,
      masterialColumns: materialFields, // +关联物料表头数据
      materialBillFields: {}, // 产品关联物料表头
      cloudwarehouse: false,
      quantityStatistics: {},
      // 埋点需要传名称
      rightSystemTabs: {
        record: {
          title: this.$t('common.base.dynamicInfo')
        },
        product: {
          title: this.$t('common.base.product')
        },
        part: {
          title: this.$t('product.productPart')
        },
        wiki: {
          title: this.$t('product.productWiki')
        },
        materiel: {
          title: this.$t('product.productMateriel')
        },
        productFaultLibrary: {
          title: this.$t('product.productFaultLibrary')
        }
      },
      faultList: [],
      faultLoading: false,
      
      bannerState: {
        taskLayout: 2,
        leftActiveTab: 'product-view',
        rightActiveTab: 'record',
        tabPosition: '', // 记录tab位置  left|right
        leftTabBarList : [],
        rightTabBarList : [],
        taskLayoutTabBarList: []
      },
      formCellCount: 1,
    }
  },
  computed: {
    hidePartCollapse() {
      if(this.bannerState.taskLayout === 2) return '';

      if(this.bannerState.taskLayout === 1) {
        return this.bannerState.tabPosition === 'left' ? 'right' : 'left';
      }
    },
    rightTabBars() {
      const { record, product, part, materiel, wiki, productFaultLibrary } = this.rightSystemTabs;
      const { recordCount, productCount, partCount, wikiCount } = this.statistics;
      const { materielCount } = this.quantityStatistics;
    
      return [
        { position: 'right', tabLabel: `${record.title}(${recordCount || 0})`, tabName: 'record', tabShow: true, disabled: true }, // 动态信息
        { position: 'right', tabLabel: `${product.title}(${productCount || 0})`, tabName: 'product', tabShow: true }, // 产品
        { position: 'right', tabLabel: `${part.title}(${partCount || 0})`, tabName: 'part', tabShow: !this.cloudwarehouse }, // 产品备件
        { position: 'right', tabLabel: `${materiel.title}(${materielCount || 0})`, tabName: 'material', tabShow: this.cloudwarehouse }, // 产品物料清单
        { position: 'right', tabLabel: `${wiki.title}(${wikiCount || 0})`, tabName: 'wiki', tabShow: this.cloudwarehouse }, // 产品知识库
        { position: 'right', tabLabel: `${productFaultLibrary.title}`, tabName: 'productFaultLibrary', tabShow: this.isShowFaultLibrary }, // 产品故障库
      ];
    },
    
    catalogId() {
      return getUrlObj.id;
    },
    /** 
     * @description 客户字段 
     */
    customerField() {
      return this.fields.filter(f => f.fieldName === 'customer')[0];
    },
    /** 
     * @description 客户字段配置 
     */
    customerOption() {
      return this.customerField?.setting?.customerOption || {};
    },
    /* 是否可以查看客户详情 */
    canSeeCustomer() {
      return this.initData.canSeeCus;
    },
    /** 工单类型设置 */
    taskType() {
      return this.initData?.taskType || {};
    },
    /* 该登录账户是否是工单负责人 */
    isExecutor() {
      let executor = this.task.executor || {};
      return executor.userId == this.loginUser.userId;
    },
    /* 该登录账户是否是工单创建人 */
    isCreator() {
      let createUser = this.task.createUser || {};
      return createUser.userId == this.loginUser.userId;
    },
    /* 工单编辑权限 */
    editAuth() {
      return this.hasAuth('TASK_EDIT');
    },
    /** 
     * @description 允许打开客户详情
     */
    allowOpenCustomerView() {
      return !this.isEncryptField(this.customer.name) && this.canSeeCustomer;
    },
    /** 
     * @description 联系人
     */
    lmName() {
      let lmName = this.task.tlmName || this.customer.lmName;

      if (lmName) return this.isEncryptField(lmName) ? ENCRYPT_FIELD_VALUE : lmName;

      return '';
    },
    /** 
     * @description 联系电话
     */
    lmPhone() {
      let lmPhone = this.task.tlmPhone || this.customer.lmPhone;

      if (this.lmName) return this.isEncryptField(this.lmName) ? ENCRYPT_FIELD_VALUE : lmPhone;

      return '';
    },
    /** 
     * @description 显示拨打电话
     * 1. 开通呼叫中心
     * 2. 且联系人未加密
     */
    showCallPhone() {
      let notEncrypt = !this.isEncryptField(this.lmName);
      return this.lmPhone && this.hasCallCenterModule && notEncrypt;
    },
    /** 
     * @description 地址
     */
    address() {
      let {
        validAddress,
        taddress,
        isEncryptTaddress
      } = this.task;

      if (validAddress) return isEncryptTaddress ? ENCRYPT_FIELD_VALUE : Filter.prettyAddress(taddress);

      return '';
    },
    /**
     * @description 显示折叠按钮
     * 审核结算、客户评价、附加组件有任一存在即显示
     */
    showCollapse() {
      return true;
    },
    messageConfig() {
      return this.initData?.messageConfig || {};
    },
    showTaskRecordTemplate() {
      return this.messageConfig.taskRemark === true
    },
    /* 是否显示服务报告 根据版本控制的 */
    isShowReport() {
      return this._isShowTaskServiceReport
    },
    // 编辑产品类型的权限
    editCatalog(){
      return this.auths.PRODUCT_CATALOG_EDIT===3
    },
    // 删除产品类型的权限
    deleteCatalog(){
      return this.auths.PRODUCT_CATALOG_DELETE===3
    },
    // 故障库
    isShowFaultLibrary() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.NEW_FAULT_LIBRARY || false
    },
  },
  methods: {
    async initBanner() {
      try {
        await this.initFormViewCell()
        // 通栏模式tabPosition默认left
        if (this.bannerState.taskLayout === 1) {
          this.bannerState.tabPosition = 'left'
        }
        let leftTabBarList = [
          { position: 'left', tabLabel:this.$t('product.productType.text.text3'), tabName: 'product-view', tabShow: true}, // 产品信息
        ]
        let rightTabBarList = this.rightTabBars;
        // 读取缓存tabbar修改右栏tabbar配置
        let { TabBarListItemKey:tabName, TabBarListItemShow:tabShow} = BaseTabBarUsualEnum;
        let params = {
          equipment:StorageHttpParamsForTerminalType.PC,
          bizType:StorageHttpParamsForModuleType.Product,
          bizTypeId:`productType_${getUrlObj.id}`
        }
        // 获取tabbar用户行为缓存/*  */
        let storageList = await getStorageForDetailTabbar(params);
        if(storageList.status !== 0) {
          throw storageList.message
        }
        let storageList_ = storageList.data.map(item=>{
          const { cardId, checked} = item;
          return {
            [tabName]:cardId,
            [tabShow]:checked
          }
        })
        rightTabBarList = computedTabList(rightTabBarList, storageList_)
        this.bannerState.leftActiveTab = leftTabBarList[0].tabName;
        this.bannerState.leftTabBarList = leftTabBarList;
        this.bannerState.rightActiveTab = rightTabBarList[0].tabName;
        this.bannerState.rightTabBarList = rightTabBarList;
      } catch (error) {
        console.warn(error, 'error try catch getStorageForDetailTabbar');
      }
    },
    tabBarChangeItem (item) {
      let { TabBarListItemKey:tabName } = BaseTabBarUsualEnum;
      let { position } = item
      this.bannerState.tabPosition = position
      // 通栏导航和左侧导航共用leftActiveTab数据
      if (this.bannerState.taskLayout === 1 || position == 'left') {
        this.bannerState.leftActiveTab = item[tabName];
      }
      // 右侧导航
      if (position == 'right') {
        this.bannerState.rightActiveTab = item[tabName];
        // 故障库
        this.rightActiveTabClick()
      }
    },
    tabBarUpdateList(list){
      const { TabBarCardInfoType, TabBarListItemKey:tabName, TabBarListItemShow:tabShow } = BaseTabBarUsualEnum;
      let list_ = list.map(item=>{
        return {
          cardId: item.type == TabBarCardInfoType ? item.id : item[tabName],
          checked: item[tabShow]
        }
      })
      let params = {
        equipment:StorageHttpParamsForTerminalType.PC,
        bizType:StorageHttpParamsForModuleType.Product,
        bizTypeId: `productType_${getUrlObj.id}`,
        cardList:list_
      }
      // 存储右栏tabbar
      setStorageForDetailTabbar(params)
    },
    openBaseLayoutModal() {
      this.$refs.bizLayoutModal.open()
    },
    changeTaskDetailLayout(type, columns) {
      this.bannerState.leftActiveTab = this.bannerState.leftTabBarList[0].tabName
      this.bannerState.taskLayout = type
      this.bannerState.tabPosition = 'left'
      if (type === 2) {
        this.bannerState.rightActiveTab = this.bannerState.rightTabBarList[0].tabName
      }
      this.formCellCount = columns * 1
    },
    async initFormViewCell(){
      const { getSystemViewLayout } = useStateSystemViewLayout()
      const count = await getSystemViewLayout()
      this.bannerState.taskLayout = count.baseLayout || 2;
      this.formCellCount = count.formCellCount || 1;
    },
    /** 更新右侧tab 数据 */
    upDataRightTabBarList() {
      this.bannerState.rightTabBarList.forEach(item => {
        const tab = this.rightTabBars.find(ele => ele.tabName === item.tabName);
        if (tab) {
          item.tabLabel = tab.tabLabel;
        }
      });
    },
    // 附加组件数量统计
    async fetchCount() {
      try {
        await amountCount({
          catalogId: this.catalogId
        }).then(res => {
          if (!res.success) {
            return this.$notify.error({
              message: res.message,
              duration: 2000,
            });
          }
          this.quantityStatistics = res.result;
        })
      } catch (error) {
        console.warn(error, 'error try catch');
      }
     
    },
    // 系统灰度接口
    async getSystemGrayInfo(){
      try {
        await getAllGrayInfo().then(res=>{
          this.cloudwarehouse = res.cloudwarehouse;
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 点击关联物料
    handleAddMaterial() {
      this.$refs.materialDialogRef.openMaterialList();
    },
    // 关联物料
    async handleSubmitMaterial(val) {
       
      if (!val.length) return;

      let materielList = val.map(item => {
        return {
          materielId: item.id,
          materielName: item.name,
          materielNum: Number(item.num),
        }
      })

      relationMateriel({
        catalogId: getUrlObj.id,
        materielList
      }).then(res => {
        if (!res.success) {
          return this.$notify.error({
            message: res.message,
            duration: 2000,
          });
        }
        this.$refs.materialBillRef.fetchMaterialList();
        this.handleDeleteMaterial();
      })
    },
    // 删除物料 更新日志和数量的统计
    async handleDeleteMaterial() {
      try {
        await this.fetchCount();
        await this.reloadRecord();
      } catch(err){
        console.error(err);
      }
     
    },
    async getProductFields(){
      try{
        let {data} = await getProductFields({isFromSetting: false});
        const customer=data.find(item=>item.fieldName==='customer');
        if(customer && customer.setting && customer.setting.customerOption){
          this.showAddress=customer.setting.customerOption.address;
          this.showLinkman=customer.setting.customerOption.linkman;
        }
      }catch(err){
        console.error(err);
      }
    },
    // 跳转到上级分类
    toFather(id){
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `productV2_catalog_view_${id}`,
      //   title: '产品类型详情',
      //   close: true,
      //   url: `/productV2/catalog/view?id=${id}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductV2CatalogView,
        key: id,
        params: `id=${id}`,
        fromId
      })
    },
    // 关联备件 知识库 产品
    onAssociated(type) {
      this.dialogType = type;
      this.changeVisibleProp(true);
    },
    changeVisibleProp (e) {
      this.visibleProp = e;
    },
    dialogConfirm(data) {
      this.$refs.publicDialog.changeBtnLoading(true);
      if(this.dialogType == 'linkProduct') return this.relationProduct(data.nowChooseArr);
      let type = this.dialogType == 'linkPart' ? 'part' : 'wiki';

      this.link(type, data.nowChooseArr)
    },
    /* 刷新动态记录 */
    async reloadRecord(){
      try {
        this.$refs.producMmenuInfoRecord.searchRecord()
        await this.getProductMenuStatisticsReq();
        this.upDataRightTabBarList();
      } catch (error) {
        console.warn(error, 'error try catch');
      }
    },
    /**获取动态信息 */
    async getProductMenuStatisticsReq(state) {
      try {
        await productMenuStatistics({
          id: getUrlObj.id
        }).then(res_ => {
          this.statistics = res_.result || {}
          if(state) {
            this.upDataRightTabBarList()
          }
        })
      } catch (error) {
        console.warn(error, 'error try catch');
      }
    },
    /**
     * @description: 关联备件或者知识库
     * @param {*} type part备件 wiki知识库
     * @param {*} data 关联的数据
     */
    link (type, data) {
      setPagerelationPartOrWiki({
        catalogId: getUrlObj.id,
        relationIds: data,
        type,
      })
        .then((res) => {
          if (res.code == 0) {
            this.$message.success(this.$t('product.productType.tips.tip30'))           
            this.changeVisibleProp(false);

            setTimeout(()=>{
              // window.location.reload();
              console.log(type);
              if(type==='part') this.$refs.linkPart.reflash();
              if(type==='wiki') this.$refs.linkWiki.reflash();  
              this.reloadRecord()      
            }, 500)
          } else {
            this.$notify.error({
              title: this.$t('common.base.tip.httpIsError'),
              message: res.message,
              duration: 2000,
            });
          }
        })
        .finally(() => {
          this.changeVisibleProp(false);
          this.$refs.publicDialog.changeBtnLoading(false);
        });
    },
    // 关联产品
    relationProduct(data){
      const params={
        catalogId:getUrlObj.id,
        productIds:data
      }
      relationProduct(params).then(res=>{
        if (res.code == 0) {
          this.$message.success(this.$t('product.productType.tips.tip30'))           
          this.changeVisibleProp(false);

          setTimeout(()=>{
            this.$refs.linkProduct.reflash();
          }, 500)
        } else {
          this.$notify.error({
            title: this.$t('common.base.tip.httpIsError'),
            message: res.message,
            duration: 2000,
          });
        }
      }).finally(() => {
        this.changeVisibleProp(false);
        this.$refs.publicDialog.changeBtnLoading(false);
        this.getProductMenuStatisticsReq(true)
      });
    },
    // 是否含有某一指定权限
    hasAuth(keys) {
      // return AuthUtil.hasAuth(this.permission, keys);
    },
    // 编辑跳转
    goEdit() {
      const id = this.task.id;
      window.location.href = this.editAuth ? `${this.$resourcePrefix}/task/edit/${id}` : `${this.$resourcePrefix}/task/noFilterEdit/${id}`;
    },
    // DING
    ding(all = true) {
      let {
        id,
        taskNo,
        executor,
        synergies
      } = this.task;

      let users = [];
      users.push(executor.staffId);

      // 所有人(工单负责人和协同人)
      if (all && synergies && synergies.length) {
        synergies.forEach(item => users.push(item.staffId));
      }

      window.parent.send_link_ding_message(users, taskNo, id);
    },
    /** 
     * @description 打开客户详情
     */
    openCustomerView() {
      if (!this.allowOpenCustomerView) return;

      let fromId = window.frameElement.getAttribute('id');
      const customerId = this.customer.id;

      if (!customerId) return;

      // this.$platform.openTab({
      //   id: `customer_view_${customerId}`,
      //   title: '客户详情',
      //   close: true,
      //   url: `/customer/view/${customerId}?noHistory=1`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        params: 'noHistory=1',
        fromId
      })
    },
    /**
     * @description 拨打电话
     */
    async makePhoneCall() {
      // 未开通呼叫中心 taskType: 'task'
      if (!this.hasCallCenterModule) return;
      let phone = this.task.tlmPhone || this.customer.lmPhone;
      if (!phone) return;

      ctiCallOut(phone)
    },
    /**
     * @description 是否加密字段
     */
    isEncryptField(value) {
      return value === ENCRYPT_FIELD_VALUE;
    },

    dleteData() {
      this.$confirm(this.$t('product.productType.tips.tip31'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      }).then(() => {
        delTreeList({
          ids: [this.dataInfo.id]
        }).then((res) => {
          if (res.code != 0) {
            this.$notify.error({
              title: this.$t('common.base.requestError'),
              message: res.message,
              duration: 2000,
            });
          } else {
            const id = window.frameElement.dataset.id;
            const fromId = window.frameElement.getAttribute('fromid');
            this.$platform.closeTab(id);
            this.$platform.refreshTab(fromId);
          }
        }).catch()
      })
    },
    alterData() {
      window.location.href = `${this.$resourcePrefix}/productV2/catalog/edit?id=${this.dataInfo.id}`;
    },
    creatData() {
      // this.$platform.openTab({
      //   id: 'productV2_catalog_edit',
      //   title: '产品类型管理',
      //   close: true,
      //   reload: true,
      //   url: '/productV2/catalog/edit',
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductCatalogCreate
      })
    },
    getBtnsTrackData(id, data) {
			return this.$track.formatParams(id, data, 'DETAIL_BTNS_GROUP')
		},

    rightActiveTabClick() {
      const title = this.rightSystemTabs[this.bannerState.rightActiveTab]?.title
      title && this.$track.clickStat(this.$track.formatParams('DETAIL_ADD_ONS_TABS', title))

      if (this.bannerState.rightActiveTab === 'productFaultLibrary') {
        this.fetchFaultLibrary()
      }
    },
    // 获取故障树
    async fetchFaultLibrary(){
      try {
        this.faultLoading = true;
        let res = await productTypeFaultRecord({
          enterState: 1,
          relIdList: [this.dataInfo?.id],
          relType: 1
        })

        if(res.status === 0){
          this.switchDataList(res.data || [])
          this.faultList = res.data || []
        }else{
          this.$notify.error({
            title: this.$t('common.base.toast'),
            message: res.message,
            duration: 2000,
          });
        }
      } catch(err) {
        console.log('fetchFaultLibrary => err', err)
      } finally {
        this.faultLoading = false;
      }
    },
    switchDataList(data){
      // 将解决方案solutionList改为childrenList，且把解决方案的元素添加faultDesc字段值为solutionDesc字段
      data.map(item => {
        const { solutionList, childrenList } = item

        if(solutionList?.length){
          solutionList.map(content => {
            content.faultDesc = content.solutionDesc
            content.faultLabel = content.faultLabel || this.$t('faultLibrary.solution')
          })

          item.childrenList = item.childrenList ? [ ...item.childrenList, ...solutionList ] : [ ...solutionList ]
        }

        if(childrenList?.length){
          this.switchDataList(item.childrenList)
        }
      })
    },
    async getPageInfoReq() {
      await getPageInfo({ id: getUrlObj.id}).then(res => {
        if (res.code == 0) {
          this.auths=res.result.auths;
          const productVideo=res.result.catalogInfo.productVideo || [];
          res.result.catalogInfo.productVideo = productVideo.filter(item=>item);
          res.result.catalogInfo.productExplain = res.result.catalogInfo.productExplain || []
         
          this.fieldHideIdArr = res.result.selectField || [];
          this.isHaveDetails = res.result.catalogInfo.conData == 1;
          this.$refs.producMmenuInfoRecord && this.$refs.producMmenuInfoRecord.initRecord(res.result.catalogInfo.id);
          this.treePath = res.result.treePath;

          getProductMenuField().then(async res_ => {
            if (res_.code == 0) {

              let fields = (res_.result || []).filter(field => !(field.isHidden == 1 || field.isVisible == false));
              fields = fields.map((item) => {
                if ((res.result.selectField.length && !item.isSystem && res.result.selectField.some(item_=>item_ == item.id)) || item.fieldName == 'product_menu_part' || item.fieldName == 'product_menu_wiki' || item.fieldName === 'productMaterialsBill')
                  item['isHidden'] = true;
                else item['isHidden'] = false;
                return item;
              })

              fields.splice()
              fields.push({
                displayName: this.$t('common.base.createUser'),
                fieldName: 'createUserName'
              }, {
                displayName: this.$t('common.base.createTime'),
                isSystem: 1,
                fieldName: 'createTime',
                formType: 'datetime'
              })

              this.fields = [...fields];

              this.fields.forEach(field => {

                if (field.fieldName == 'attachment') {
                  let {
                    isEncryptAttachment,
                    attachment
                  } = this.task

                  // 系统附件加密
                  if (isEncryptAttachment) {
                    this.task.attachment = ENCRYPT_FIELD_VALUE;
                  } else {
                    this.task.attachment = attachment.filter(item => !item.receipt);
                  }
                }
                
                // 产品物料清单
                if (field.fieldName == 'productMaterialsBill') {
                  this.materialBillFields = field;
                }
              })
              // 处理富文本
              res.result.catalogInfo = await FormUtil.initRichTextContent(this.fields, res.result.catalogInfo)
              this.$set(this, 'dataInfo', res.result.catalogInfo || {})
            }
          })
        } else {
          this.$notify.error({
            title: this.$t('common.base.tip.httpIsError'),
            message: res.message,
            duration: 2000,
          });
        }
      }).finally(() => {

      })
    }
  },
  async mounted() {
    try {
      this.loading = true
      await this.getPageInfoReq()
      await this.getProductMenuStatisticsReq();
      await this.getSystemGrayInfo();
      await this.fetchCount()
      this.getProductFields();  
      await this.initBanner()
    } catch (error) {
      console.error('fetch goods Detail error', error);
    } finally {
      this.loading = false;
    }
  },
  created() {
    // 折叠面板缓存
    let collapse = sessionStorage.getItem(`product_menu_collapse_${getUrlObj.id}`);
    let collapseDirection = sessionStorage.getItem(`product_collapseDirection_${getUrlObj.id}`);
    this.collapse = JSON.parse(collapse || 'true');
    this.collapseDirection = collapseDirection || '';
  },
  beforeDestroy() {

  },
  watch: {
    collapse(newValue) {
      sessionStorage.setItem(`product_menu_collapse_${getUrlObj.id}`, newValue);
    },
    collapseDirection(newValue) {
      sessionStorage.setItem(`product_collapseDirection_${getUrlObj.id}`, newValue);
    },
    "bannerState.leftTabBarList": {
      handler() {
        this.bannerState.taskLayoutTabBarList = cloneDeep([...this.bannerState.leftTabBarList,...this.bannerState.rightTabBarList].filter(item => item.tabShow));
      },
      deep: true
    },
    "bannerState.rightTabBarList": {
      handler() {
        this.bannerState.taskLayoutTabBarList = cloneDeep([...this.bannerState.leftTabBarList,...this.bannerState.rightTabBarList].filter(item => item.tabShow));
      },
      deep: true
    },
  },
  components: {
    ProductMenuInfoRecord,
    ProductMenuView,
    MiniTable,
    PublicDialog,
    NoDataView,
    MaterialDialog,
    FormMaterialsBillView,
    TreeList,
    BaseBarV3,
    BaseTileLayoutTabBar,
    FormCellChange,
  }
}